package com.jnu.HomeworkApplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jnu.HomeworkApplication.data.Book;
import com.jnu.HomeworkApplication.data.DataStorage;

import java.util.List;


public class BookFragment extends Fragment {

    private List<Book> Books;
    private BookFragment.MyRecycleViewAdapter BookAdapter;
    private DataStorage dataStorage;

    public BookFragment() {
        // Required empty public constructor
    }

    public static BookFragment newInstance() {
        BookFragment fragment = new BookFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_book, container, false);
        initData();

        FloatingActionButton floatingActionButton = rootView.findViewById(R.id.add);
        floatingActionButton.setOnClickListener(v -> {
            Intent intent = new Intent(this.getContext(), EditBookActivity.class);
            intent.putExtra("position", 0);
            launcherAdd.launch(intent);
        });

        //Log.e("Book content",Integer.toString(Books.get(0).getCoverResourceId()));
        RecyclerView recyclerView = rootView.findViewById(R.id.recycle_view_books);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        BookAdapter = new BookFragment.MyRecycleViewAdapter(Books);
        recyclerView.setAdapter(BookAdapter);

        return rootView;
    }



    ActivityResultLauncher<Intent> launcherAdd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            int resultCode = result.getResultCode();
            if (resultCode == 514) {
                Intent data = result.getData();
                assert data != null;
                String bookName = data.getStringExtra("Book_Name");
                int position = data.getIntExtra("position", 0);
                int bookId = data.getIntExtra("Book_id",R.drawable.book_no_name);
                Books.add(position, new Book(bookName, bookId));
                dataStorage.SaveData();
                BookAdapter.notifyItemInserted(position);
            }
        }
    });

    ActivityResultLauncher<Intent> launcherEdit = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            int resultCode = result.getResultCode();
            if (resultCode == 514) {
                Intent data = result.getData();
                assert data != null;
                String bookName = data.getStringExtra("Book_Name");
                int position = data.getIntExtra("position", 0);
                int bookId = data.getIntExtra("Book_id",R.drawable.book_no_name);
                Books.get(position).setTitle(bookName);
                Books.get(position).setCoverResourceId(bookId);
                dataStorage.SaveData();
                BookAdapter.notifyItemChanged(position);
            }
        }
    });


/*
    被废弃的启动项
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 514)
        {
            assert data != null;
            String bookName = data.getStringExtra("Book_Name");
            int position = data.getIntExtra("position",0);
            if(requestCode == 114){
                Books.add(position,new Book(bookName,R.drawable.book_no_name));
                BookAdapter.notifyItemInserted(position);
            }
            else if(requestCode == 1919)
            {
                Books.get(position).title = bookName;
                BookAdapter.notifyItemChanged(position);
            }
        }
    }

 */

    private void initData() {
        dataStorage = new DataStorage(this.getContext());
        Books = dataStorage.loadData();
    }

    private class MyRecycleViewAdapter extends RecyclerView.Adapter {

        private final List<Book> Books;

        public MyRecycleViewAdapter(List<Book> Books) {
            this.Books = Books;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_item, parent, false);

            return new BookFragment.MyRecycleViewAdapter.ViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            BookFragment.MyRecycleViewAdapter.ViewHolder Holder = (BookFragment.MyRecycleViewAdapter.ViewHolder) holder;
            Holder.getImageView().setImageResource(Books.get(position).getCoverResourceId());
            Holder.getTextView().setText(Books.get(position).getTitle());

        }

        @Override
        public int getItemCount() {
            return Books.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
            ImageView imageView;
            TextView textView;

            public ViewHolder(View itemView) {
                super(itemView);
                this.imageView = itemView.findViewById(R.id.image_view_book_cover);
                this.textView = itemView.findViewById(R.id.text_view_book_title);

                itemView.setOnCreateContextMenuListener(this);
            }

            public ImageView getImageView() {
                return imageView;
            }

            public TextView getTextView() {
                return textView;
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                MenuItem menuItemAdd = menu.add(Menu.NONE, 1, 1, "Add");
                MenuItem menuItemEdit = menu.add(Menu.NONE, 2, 2, "Edit");
                MenuItem menuItemDelete = menu.add(Menu.NONE, 3, 3, "Delete");

                menuItemAdd.setOnMenuItemClickListener(this);
                menuItemEdit.setOnMenuItemClickListener(this);
                menuItemDelete.setOnMenuItemClickListener(this);
            }

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int position = getAdapterPosition();

                switch (item.getItemId()) {
                    case 1:
                        addItem(position);
                        break;
                    case 2:
                        editItem(position);
                        break;
                    case 3:
                        deleteItem(position);
                        break;
                }
                Toast.makeText(BookFragment.this.getContext(), "点击" + item.getTitle(), Toast.LENGTH_LONG).show();
                return false;
            }

            private void deleteItem(int position){
                Books.remove(position);
                dataStorage.SaveData();
                BookFragment.MyRecycleViewAdapter.this.notifyItemRemoved(position);
            }



            private void editItem(int position) {
                Intent intent = new Intent(BookFragment.this.getContext(), EditBookActivity.class);
                intent.putExtra("Book_Name", Books.get(position).getTitle());
                intent.putExtra("position", position);
                intent.putExtra("Book_id",Books.get(position).getCoverResourceId());
                launcherEdit.launch(intent);
            }

            private void addItem(int position) {
                Intent intent = new Intent(BookFragment.this.getContext(), EditBookActivity.class);
                intent.putExtra("position", position);
                launcherAdd.launch(intent);
            }
        }
    }
}